<template>
	<view>
		<u-navbar back-icon-color="#fff" :background="background">
			<view class="slot-wrap u-padding-left-20">
				<u-search placeholder="请输入姓名搜索" @change="searchChange" @custom="confirmSearch" @search="confirmSearch" v-model="keyword"></u-search>
			</view>
		</u-navbar>
		
		<u-tabs 
			:list="tabsList" 
			active-color="#849ee3" 
			inactive-color="#606266" 
			:is-scroll="false" 
			:current="current"
			@change="uTabsChange">
		 </u-tabs>
		
		<view class="container u-margin-top-80">
			<template v-if="searchData.length !== 0">
				<view v-if="userLists.length>0">
					<block v-for="(item,index) in searchData" :key="index">
						<view class="user-item white-bg z-b-r u-margin-bottom-20 u-padding-20 z-font-lg u-flex">
							<view class="u-flex-1">
								<view class="">
									<text>姓名：</text>
									<text>{{ item.name }}({{ item.sex }})</text>
									<u-tag :text="item.workStatus === 0 ? '空闲' : '工作'" shape="circle" :type="item.workStatus === 0 ? 'info' : 'success'" />
								</view>
								<view class="">
									<text>联系电话：</text>
									<text>{{item.phone}}</text>
								</view>
								<view class="">
									<text>家庭住址：</text>
									<text>{{item.address}} {{ item.detailAddre }}</text>
								</view>
							</view>
							<view>
								<u-tag @click="selectWorkerHandle(item)" :text="worker_ids.findIndex(wkID=>wkID===item.wkID) == -1 ? '点击选择' : '取消选择'"
								 :type="worker_ids.findIndex(wkID=>wkID===item.wkID) == -1 ? 'info' : 'primary'" shape="square" />
							</view>
						</view>
					</block>
				</view>
				
				<view v-else>
					<empty-data></empty-data>
				</view>
				
			</template>
			<template v-else>
				<view v-if="userLists.length>0">
					<block v-for="(item,index) in userLists" :key="index">
						<view class="user-item white-bg z-b-r u-margin-bottom-20 u-padding-20 z-font-lg u-flex">
							<view class="u-flex-1">
								<view class="">
									<text>姓名：</text>
									<text>{{ item.name }}({{ item.sex }})</text>
									<u-tag size="mini" :text="item.workStatus === 0 ? '空闲' : '工作'" shape="circle" :type="item.workStatus === 0 ? 'info' : 'success'" />
								</view>
								<view class="">
									<text>联系电话：</text>
									<text>{{item.phone}}</text>
								</view>
								<view class="">
									<text>家庭住址：</text>
									<text>{{item.address}} {{ item.detailAddre }}</text>
								</view>
							</view>
							<view>
								<u-tag 
									@click="selectWorkerHandle(item)" 
									:text="worker_ids.findIndex(itemID=>itemID.wkID===item.wkID) == -1 ? '点击选择' : '取消选择'"
									:type="worker_ids.findIndex(itemID=>itemID.wkID===item.wkID) == -1 ? 'info' : 'primary'" shape="square" />
							</view>
						</view>
					</block>
				</view>
				
				<view v-else>
					<empty-data tipText="无用户数据"></empty-data>
				</view>
				
			</template>
			
			<bottom-bar>
				<u-button :disabled="disabledBtn" type="primary" @click="confirmSelectWorker">确认选择</u-button>
			</bottom-bar>
			
		</view>
		
		<!-- 提示 -->
		<u-top-tips ref="uTips"></u-top-tips>
		<u-toast ref="uToast" />
		<!-- 模态框 -->
		<u-modal v-model="showModal" @confirm="confirmDeleteWK" content="是否确认删除该员工" show-cancel-button="true"></u-modal>
		<u-modal v-model="showModal2" @confirm="confirmSelectOtherWK" content="该员工已在其他项目工作,确认选择吗" show-cancel-button="true"></u-modal>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex";
	export default {
		data() {
			return {
				background: {
					backgroundColor: '#fff',
				},
				tabsList: [
					{
						name: '空闲',
						id:0
					},
					{
					name: '工作中',
					id:1
				}],
				current:0,
				showModal: false,
				showModal2:false,
				userLists: [],
				worker_ids: [],
				disabledBtn: false,
				projectID:"",
				curProjectSalaryWay:"",
				curWkID:"",
				IDandSalaryWay:{},
				searchData:[],
				keyword:"",
				workers:[]  //绑定的员工
			}
		},
		onLoad(params) {
			this.projectID = params.projectID;
			this.curProjectSalaryWay = params.salaryWay;
			this.getUserDataList();
		},
		computed: {
			...mapState({
				token: "token",
				userID:"userID",
				pm_company:"pm_company"
			})
		},
		methods: {
			uTabsChange(index){
				this.current = index;
				this.getUserDataList();
			},
			selectWorkerHandle(user) { //选择||取消选择单个工人
				let curSelectID = {
					wkID:user.wkID,
					salaryWay:this.curProjectSalaryWay,
					drillDeepCount:0,
					signCountDay:0,
					drillID:""
				},
				wkIDIndex = this.worker_ids.findIndex(item => item.wkID === curSelectID.wkID);
				if(user.workStatus === 1 && wkIDIndex === -1){ //工作中 并且 不属于当前项目  但是又要添加或者误点
					this.selectOtherProjectWorker()
					this.IDandSalaryWay = curSelectID;
				} else if(user.workStatus === 1 && wkIDIndex !== -1){ //工作中 并且 属于当前项目  取消选择(已经工作)
					this.updateWorkerStatus(0,curSelectID.wkID)
				} else if(user.workStatus === 0 && wkIDIndex !== -1){  //刚选中 还没有确定  需要取消
					this.worker_ids.splice(wkIDIndex,1)
				} else if(user.workStatus === 0 && wkIDIndex === -1){  //需要选择
					this.worker_ids.push(curSelectID)
				}
			},
			async confirmSelectWorker() { //确认选择工人，添加到项目中
				let {worker_ids,projectID} = this
				if(worker_ids.length === 0){
					this.$refs.uToast.show({
						title: '请选择工人',
						type: 'warning'
					})
					return false;
				}
				
				this.$loading("正在分配")
				let res = await this.$network({
					api:"main",
					data:{
						action:"allotWKAdmin/allotWorkerInProject",
						data:{
							worker_ids,
							projectID
						}
					}
				})
				if(res.status === 0){
					this.updateWorkerStatus();
				}
			},
			//修改员工状态
			async updateWorkerStatus(status=1,wkID=""){
				let {worker_ids,token,projectID} = this;
				let updateWorkerStatusRes;
				if(status === 1){ //添加
					let updateWorkerStatusTask = [];
					worker_ids.forEach(item=>{
						updateWorkerStatusTask.push(this.$network({
								api:"main",
								data:{
									action:"allotWKAdmin/updateWorkerStatus",
									data:{
										status:1,
										wkID:item.wkID,
										token
									}
								}
							}))
					})
					updateWorkerStatusRes = await Promise.all(updateWorkerStatusTask);
					uni.hideLoading();
					this.$refs.uToast.show({
						title: '分配成功，返回刷新',
						type: 'success'
					})
				} else if(status === 0 && wkID !== ''){
					this.curWkID = wkID;
					this.showModal = true;
				}
			},
			//确认删除
			async confirmDeleteWK(){
				this.$loading("正在取消");
				let {worker_ids,token,projectID,curWkID} = this;
				let updateWorkerStatusRes = await this.$network({  //更改状态
					api:"main",
					data:{
						action:"allotWKAdmin/updateWorkerStatus",
						data:{
							status:0,
							wkID:curWkID,
							token
						}
					}
				})
				
				if(updateWorkerStatusRes.status === 0) {
					this.deleteProjectWorker(curWkID)
				}
			},
			//删除项目里面的员工
			async deleteProjectWorker(wkID){
				let {token,projectID} = this;
				let deleteProWK = await this.$network({
					api:"main",
					data:{
						action:"allotWKAdmin/deleteProjectInWorker",
						data:{
							token,
							projectID,
							wkID
						}
					}
				})
				
				uni.hideLoading();
				if(deleteProWK.status === 0){
					this.worker_ids.splice(this.worker_ids.findIndex(item=>item.wkID===wkID),1);
					this.userLists[this.userLists.findIndex(item=>item.wkID === wkID)].workStatus = 0;
					this.$refs.uToast.show({
						title: '已删除，返回刷新',
						type: 'success'
					})
				}
			},
			//
			selectOtherProjectWorker(){
				this.showModal2 = true;
			},
			async confirmSelectOtherWK(){
				let {token,projectID,IDandSalaryWay} = this;
				this.$loading("正在更改")
				let updateFrontRes = await this.$network({
					api:"main",
					data:{
						action:"allotWKAdmin/selectOtherProjectWorker",
						data:{token,projectID,IDandSalaryWay}
					}
				})
				
				// console.log(updateFrontRes);
				uni.hideLoading();
				if(updateFrontRes.status === 0){
					this.$refs.uToast.show({
						title: '已经更改，请点击确认选择',
						type: 'success'
					})
					this.worker_ids.push(IDandSalaryWay);
				}
			},
			//获取用户数据
			async getUserDataList() {
				this.userLists = [];
				this.$loading("正在加载")
				let {token,projectID,current,userID,pm_company} = this;
				//获取当前公司 员工信息（需要项目经理绑定）
				 //列表数据，工人数据
				 this.$loading("正在加载")
				 let wkInfoTasks = [];
				 let {workers} = this;
				 let wkInfos = await this.$network({
					 api: "main",
					 data: {
					 	action:"allotWKAdmin/getUserDataByCompanyID",
					 	data:{token,pm_company,workStatus:this.tabsList[current].id}
					 } 
				 })
				 
				 uni.hideLoading();
				 if(wkInfos.status === 0){
					 this.userLists = wkInfos.data
				 }

				//当前项目员工ID
				this.$loading("正在校验")
				let workerIDsRes = await this.$network({ 
					api:"main",
					data:{
						action:"allotWKAdmin/getProjectWKID",
						data:{projectID,token}
					}
				})
				if(workerIDsRes.status === 0) this.worker_ids = workerIDsRes.data[0].worker_ids;
				uni.hideLoading()
			},
			//搜索
			async confirmSearch(){
				let {keyword,current} = this;
				if(keyword === ""){
					this.$refs.uToast.show({
						title: '请输入员工姓名',
						type: 'warning'
					})
					return false;
				}
				
				this.$loading("正在搜索")
				let res = await this.$network({  //列表数据
					api: "main",
					data: {
						action:"search/searchUserDataByName",
						data:{workStatus:this.tabsList[current].id,keyword}
					}
				})
				uni.hideLoading();
				if(res.status === 0){
					this.searchData = res.data;
				} else {
					this.$refs.uToast.show({
						title: '没有该员工',
						type: 'warning'
					})
				}
			},
			searchChange(){
				if(this.keyword === '') this.searchData = [];
			}
		}
	}
</script>

<style scoped lang="scss">
	
</style>
